package com.nervenets.shopping.service.impl;

import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.bean.entpay.EntPayResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.nervenets.general.service.impl.BaseServiceImpl;
import com.nervenets.general.utils.JodaUtils;
import com.nervenets.general.utils.StringUtils;
import com.nervenets.shopping.hibernate.dao.BonusSharingDao;
import com.nervenets.shopping.hibernate.domain.order.BonusSharing;
import com.nervenets.shopping.hibernate.domain.order.BonusSharingItem;
import com.nervenets.shopping.hibernate.domain.user.User;
import com.nervenets.shopping.hibernate.domain.user.UserWxId;
import com.nervenets.shopping.service.BonusSharingItemService;
import com.nervenets.shopping.service.BonusSharingService;
import com.nervenets.shopping.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BonusSharingServiceImpl extends BaseServiceImpl<BonusSharing, BonusSharingDao> implements BonusSharingService {
    @Resource
    private BonusSharingItemService bonusSharingItemService;
    @Resource
    private WxPayService wxPayService;
    @Resource
    private UserService userService;

    @Override
    public BonusSharing findTop1Unfinished() {
        return dao.findTop1ByFinishedIsFalseOrderById();
    }

    @Override
    public void handleTop1Unfinished() {
        BonusSharing bonusSharing = findTop1Unfinished();
        if (null != bonusSharing) {
            List<User> users = userService.findAll((predicates, root, query, builder) -> {
                predicates.add(builder.isTrue(root.get("inviter")));
                predicates.add(builder.isTrue(root.get("enable")));
            });
            boolean bonusSharingFinished = true;
            if (!users.isEmpty()) {
                long bonus = bonusSharing.getBonus();
                long pre = bonus / users.size();

                for (User user : users) {
                    BonusSharingItem sharingItem = bonusSharingItemService.findBonusSharingItem(bonusSharing, user.getId());
                    if (null == sharingItem) sharingItem = BonusSharingItem.builder()
                            .bonusSharing(bonusSharing)
                            .createBy(user.getId())
                            .finished(false)
                            .build();
                    if (!sharingItem.isFinished()) {
                        UserWxId userWxId = userService.findUserWxId(user, wxPayService.getConfig().getAppId());
                        if (null != userWxId) {
                            EntPayRequest entPayRequest = EntPayRequest.newBuilder()
                                    .partnerTradeNo(StringUtils.randomString(6).toUpperCase() + JodaUtils.getTimestamp())
                                    .openid(userWxId.getOpenId())
                                    .checkName("NO_CHECK")
                                    .amount(Math.toIntExact(pre))
                                    .description("分红奖励")
                                    .spbillCreateIp("121.199.15.222")
                                    .build();
                            try {
                                EntPayResult entPayResult = wxPayService.getEntPayService().entPay(entPayRequest);
                                if ("SUCCESS".equals(entPayResult.getReturnCode()) && "SUCCESS".equals(entPayResult.getResultCode())) {
                                    sharingItem.setFinished(true);
                                    sharingItem.setRemark("拼团失败奖励发放成功");
                                } else {
                                    sharingItem.setRemark("拼团失败奖励失败：" + entPayResult.getErrCodeDes());
                                    bonusSharingFinished = false;
                                }
                            } catch (WxPayException e) {
                                sharingItem.setRemark("拼团失败奖励失败：" + e.getErrCodeDes());
                                bonusSharingFinished = false;
                            }
                        } else {
                            sharingItem.setRemark("未绑定微信ID。");
                        }
                        bonusSharingItemService.save(sharingItem);
                    }
                }
            }

            bonusSharing.setFinished(bonusSharingFinished);
            super.save(bonusSharing);
        }
    }
}
